<?php
class login extends Admin {

    public function index( $c ) {
        if ( $referer = R( 'referer', '' ) ) {
            $url = $this->url( null, null, array( 'referer' => $referer ) );
        } else {
            $url = $this->url();
        }
        if ( $this->admin ) {
            header( "location:{$url}" );
        }
        include $this->display( $c );
    }

    public function getcode() {
        $this->Image()->Verify();
    }

    public function validate() {

        if ( isset( $_POST[ 'verify' ] ) && strtolower( $_POST[ 'verify' ] ) != $_SESSION[ "verify" ] ) {
            $this->error( '验证码错误!' );
        }

        $author = trim( $_POST[ 'author' ] );
        $pass = md6( trim( $_POST[ 'pass' ] ) );

        $data = array( 'author' => $author );

        $this->model->table = "user";

        if ( !$result = $this->model->find( $data ) ) {
            $this->error( "{$author}账号不存在!" );
        }

        if ( $result[ 'pass' ] != $pass ) {
            $this->error( "密码错误!" );
        }

        if ( $result[ 'status' ] ) {
            $this->error( "账号已被锁定!" );
        }

        $group = $this->sort( 'user' );
        if ( !isset( $group[ $result[ 'sid' ] ] ) or $group[ $result[ 'sid' ] ][ 'alias' ] != 'system' ) {
            $this->error( "您的帐号无权限!" );
        }

        // 更新登录时间IP
        $this->model->update( $data, array( 'lastdate' => time(), 'lastip' => S( 'ip' ) ) );

        $expire = 0;
        if ( isset( $_POST[ 'remember' ] ) ) {
            $expire = empty( $this->setting[ 'cookie_time' ] ) ? $_POST[ 'remember' ] : ( $this->setting[ 'cookie_time' ] * 3600 * 24 + time() );
        }

        // 写入登录cookie
        $cookie_value = "{$result['author']}|{$result['id']}|{$expire}";
        $cookie_value = md6( $cookie_value, 'encode' );
        setcookie( APP_COOKIE, $cookie_value, $expire, '/', APP_COOKIE_DOMAIN );
        $this->success( "登录成功!" );
    }

    public function logout() {
        if ( $this->admin ) {
            setcookie( APP_COOKIE, '', time() - ( $this->setting[ 'cookie_time' ] * 3600 * 24 ), '/', APP_COOKIE_DOMAIN );
            exit;
        }
    }
}